package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.*;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.constant.HttpStatus;
import com.zzyl.common.core.domain.AjaxResult;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateTimeZoneConverter;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.vo.DeviceDataVo;
import com.zzyl.nursing.vo.DeviceDetailVo;
import com.zzyl.nursing.vo.ProductVo;
import org.apache.commons.math3.analysis.function.Add;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.service.IDeviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 设备信息Service业务层处理
 *
 * @author zhengsuyang
 * @date 2025-10-17
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService {
    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private IoTDAClient client;
    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 查询设备信息
     *
     * @param id 设备信息主键
     * @return 设备信息
     */
    @Override
    public Device selectDeviceById(Long id) {
        return getById(id);
    }

    /**
     * 查询设备信息列表
     *
     * @param device 设备信息
     * @return 设备信息
     */
    @Override
    public List<Device> selectDeviceList(Device device) {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 新增设备信息
     *
     * @param device 设备信息
     * @return 结果
     */
    @Override
    public int insertDevice(Device device) {
        return save(device) ? 1 : 0;
    }

    /**
     * 批量删除设备信息
     *
     * @param ids 需要删除的设备信息主键
     * @return 结果
     */
    @Override
    public int deleteDeviceByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除设备信息信息
     *
     * @param id 设备信息主键
     * @return 结果
     */
    @Override
    public int deleteDeviceById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    /**
     * 从物联网平台同步产品列表
     */
    @Override
    public void syncProductList() {
        // 从IOT查询到产品列表
        ListProductsRequest request = new ListProductsRequest();
        // 从产品列表最多查询到50条数据
        request.setLimit(50);
        ListProductsResponse productsResponse = client.listProducts(request);
        // 操作失败直接抛出异常
        if (productsResponse.getHttpStatusCode() != HttpStatus.SUCCESS) {
            throw new BaseException("产品同步失败");
        }
        // 获取产品列表
        List<ProductSummary> products = productsResponse.getProducts();
        // 放到Redis缓存中
        redisTemplate.boundValueOps(CacheConstants.IOT_ALL_PRODUCT_LIST)
                .set(JSONUtil.toJsonStr(products));
    }

    /**
     * 查询所有产品列表
     *
     * @return
     */
    @Override
    public List<ProductVo> getAllProduct() {
        // 从redis获取所有的产品列表
        String strJson = redisTemplate.boundValueOps(CacheConstants.IOT_ALL_PRODUCT_LIST)
                .get();
        List<ProductVo> productVos = JSONUtil.toList(strJson, ProductVo.class);
        return productVos;
    }

    /**
     * 注册设备
     */
    @Override
    public void registerDevice(DeviceDto deviceDto) {
        // 代表新增
        int flag = 0;
        // 1.进行校验
        checkdevice(deviceDto, flag);
        // 2.注册设备到ITO
        AddDeviceRequest addDeviceRequest = new AddDeviceRequest();
        AddDevice addDevice = new AddDevice();
        addDevice.setDeviceId(deviceDto.getIotId());
        addDevice.setNodeId(deviceDto.getNodeId());
        addDevice.setDeviceName(deviceDto.getDeviceName());
        addDevice.setProductId(deviceDto.getProductKey());
        AuthInfo authInfo = new AuthInfo();
        String secret = RandomUtil.randomString(32);
        authInfo.setSecret(secret);
        addDevice.setAuthInfo(authInfo);
        addDevice.setDescription(deviceDto.getDeviceDescription());
        addDeviceRequest.setBody(addDevice);
        AddDeviceResponse addDeviceResponse = client.addDevice(addDeviceRequest);
        if (addDeviceResponse.getHttpStatusCode() != HttpStatus.CREATED) {
            throw new BaseException("IOT设备添加失败");
        }
        String deviceId = addDeviceResponse.getDeviceId();
        // 3.再注册到数据库
        Device device1 = BeanUtil.toBean(deviceDto, Device.class);
        //设备id 是IOT返回的
        device1.setIotId(deviceId);
        device1.setSecret(secret);
        device1.setRemark(deviceDto.getRemark());
        this.save(device1);
    }

    /**
     * 查询设备详细数据
     *
     * @param iotId
     * @return
     */
    @Override
    public DeviceDetailVo getDeviceInfo(String iotId) {
        // 1.先查询IOT是否有设备
        ShowDeviceRequest request = new ShowDeviceRequest();
        request.setDeviceId(iotId);
        ShowDeviceResponse response = client.showDevice(request);
        if (response.getHttpStatusCode() != HttpStatus.SUCCESS) {
            throw new BaseException("IOT中不存在设备");
        }
        // 检查设备状态，只有激活状态才能修改
        if (response.getStatus().equals("INACTIVE")) {
            throw new BaseException("设备未激活，无法修改信息");
        }
        // 2.查询本地数据库是否有设备
        LambdaQueryWrapper<Device> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Device::getIotId, iotId);
        Device device = this.getOne(queryWrapper);
        // device -> DeviceDetailVo
        if (device == null) {
            throw new BaseException("设备不存在");
        }
        DeviceDetailVo deviceDetailVo = BeanUtil.toBean(device, DeviceDetailVo.class);
        deviceDetailVo.setDeviceStatus(response.getStatus());
        String activeTimeStr = response.getActiveTime();
        LocalDateTime parse = LocalDateTimeUtil.parse(activeTimeStr, DatePattern.UTC_MS_PATTERN);
        // DateTimeZoneConverter是今天资料中提供的一个工具类
        LocalDateTime activeTime = DateTimeZoneConverter.utcToShanghai(parse);
        deviceDetailVo.setActiveTime(activeTime);
        return deviceDetailVo;
    }

    /**
     * 查看设备上报的数据
     *
     * @param iotId
     * @return
     */
    @Override
    public List<DeviceDataVo> queryServiceProperties(String iotId) {
        // 创建DeviceDataVo的list集合
        List<DeviceDataVo> dataVoList = new ArrayList<>();
        // 查询IOT是否有设备
        ShowDeviceShadowRequest request = new ShowDeviceShadowRequest();
        request.setDeviceId(iotId);
        ShowDeviceShadowResponse response = client.showDeviceShadow(request);
        if (response.getHttpStatusCode() != HttpStatus.SUCCESS) {
            throw new BaseException("该设备没有上报的数据");
        }
        DeviceShadowProperties reported = response.getShadow().get(0).getReported();
        String eventTimeStr = reported.getEventTime();
        LocalDateTime parse = LocalDateTimeUtil.parse(eventTimeStr, "yyyyMMdd'T'HHmmss'Z'");
        LocalDateTime eventTime = DateTimeZoneConverter.utcToShanghai(parse);
        // 获取集合对象
        LinkedHashMap<String, Object> linkedHashMap = (LinkedHashMap<String, Object>) reported.getProperties();
        Set<String> keySet = linkedHashMap.keySet();
        for (String key : keySet) {
            DeviceDataVo deviceDataVo = new DeviceDataVo();
            Object value = linkedHashMap.get(key);
            deviceDataVo.setFunctionId(key);
            deviceDataVo.setValue(value);
            deviceDataVo.setEventTime(eventTime);
            dataVoList.add(deviceDataVo);
        }
        return dataVoList;
    }

    /**
     * 删除设备
     *
     * @param iotId
     */
    @Override
    public void deleteDevice(String iotId) {
        // 1.删除IOT的设备信息
        DeleteDeviceRequest request = new DeleteDeviceRequest();
        request.setDeviceId(iotId);
        DeleteDeviceResponse response = client.deleteDevice(request);
        if (response.getHttpStatusCode() != HttpStatus.NO_CONTENT) {
            throw new BaseException("删除设备信息失败");
        }
        // 2.删除数据库的设备信息
        LambdaQueryWrapper<Device> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Device::getIotId, iotId);
        this.remove(queryWrapper);
    }

    /**
     * 查询产品详情(报警规则模块使用)
     *
     * @param productKey
     * @return
     */
    @Override
    public AjaxResult queryProduct(String productKey) {
        ShowProductRequest request = new ShowProductRequest();
        request.setProductId(productKey);
        ShowProductResponse response = client.showProduct(request);
        if (response.getHttpStatusCode()!=HttpStatus.SUCCESS){
            throw new BaseException("IOT查询产品失败！");
        }
        List<ServiceCapability> serviceCapabilities = response.getServiceCapabilities();
        return AjaxResult.success(serviceCapabilities);
    }

    /**
     * 修改设备信息
     *
     * @param deviceDto 设备信息
     * @return 结果
     */
    @Override
    public void updateDevice(DeviceDto deviceDto) {
        // 代表修改
        int flag = 1;
        // 设备校验
        checkdevice(deviceDto, flag);
        // 1. 获取到设备id
        String iotId = deviceDto.getIotId();
        // 2. 检查设备是否激活
        ShowDeviceRequest showDeviceRequest = new ShowDeviceRequest();
        showDeviceRequest.setDeviceId(iotId);
        ShowDeviceResponse showDeviceResponse = client.showDevice(showDeviceRequest);
        if (showDeviceResponse.getHttpStatusCode() != HttpStatus.SUCCESS) {
            throw new BaseException("设备不存在或查询失败");
        }
        // 3.修改IOT的设备信息
        UpdateDeviceRequest request = new UpdateDeviceRequest();
        // 4.设置请求体
        UpdateDevice updateDevice = new UpdateDevice();
        updateDevice.setDeviceName(deviceDto.getDeviceName());
        updateDevice.setDescription(deviceDto.getDeviceDescription());
        request.setBody(updateDevice);
        request.setDeviceId(iotId);
        UpdateDeviceResponse updateDeviceResponse = client.updateDevice(request);
        if (updateDeviceResponse.getHttpStatusCode() != HttpStatus.SUCCESS) {
            throw new BaseException("修改设备信息失败");
        }
        // 5.修改数据库的设备信息
        //  update 表名 set 字段名 where id = ?
        LambdaUpdateWrapper<Device> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(Device::getDeviceName, deviceDto.getDeviceName());
        updateWrapper.set(Device::getLocationType, deviceDto.getLocationType());
        updateWrapper.set(Device::getRemark, deviceDto.getRemark());
        updateWrapper.eq(Device::getIotId, iotId);
        this.update(updateWrapper);
    }

    /**
     * 校验设备
     */
    public void checkdevice(DeviceDto deviceDto, int flag) {

        // 1.进行校验
        // 1.1 判断设备名称是否重复
        LambdaQueryWrapper<Device> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(Device::getDeviceName, deviceDto.getDeviceName());
        Device device = this.getOne(queryWrapper1);
        if (device != null) {
            throw new BaseException("设备名称不能重复");
        }
        // 1.2 判断设备标识是否重复
        if (flag == 0) {
            LambdaQueryWrapper<Device> queryWrapper2 = new LambdaQueryWrapper<>();
            queryWrapper2.eq(Device::getNodeId, deviceDto.getNodeId());
            device = this.getOne(queryWrapper2);
            if (device != null) {
                throw new BaseException("设备标识不能重复");
            }
        }
        // 1.3 同一位置是否绑定相同产品
        LambdaQueryWrapper<Device> queryWrapper3 = new LambdaQueryWrapper<>();
        queryWrapper3.eq(Device::getLocationType, deviceDto.getLocationType());
        queryWrapper3.eq(Device::getBindingLocation, deviceDto.getBindingLocation());
        queryWrapper3.eq(Device::getProductKey, deviceDto.productKey);
        device = this.getOne(queryWrapper3);
        if (device != null) {
            throw new BaseException("同一位置不能绑定相同产品");
        }
    }
}
